﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using Fengsoft.AIBlog.Web.Code;
using Fengsoft.AIBlog.Web.Models;
namespace Fengsoft.AIBlog.Web.Controllers
{
    public class BlobInfoController:ExtensionController
    {
        private const string thumbnailDirectory="~/app_data/blob/thumbnails";
        private const int thumbnailWidth=160;
        private const int thumbnailHeight=90;
        private string GetImagePhysicalPath(string imageID)
        {
            string fileName=string.Format("{0}.jpg",imageID);
            string filePath=HostingEnvironment.MapPath(string.Format("~/app_data/blob/{0}",fileName));
            return System.IO.File.Exists(filePath)?filePath:string.Empty;
        }
        private void RemoveThumbnails(string imageID)
        {
            string thumbnailPhysicalDirectory=HostingEnvironment.MapPath(thumbnailDirectory);
            if (Directory.Exists(thumbnailPhysicalDirectory))
            {
                var fileNames=Directory.GetFiles(thumbnailPhysicalDirectory).Where(x=>x.Contains(imageID));
                foreach (string fileName in fileNames)
                {
                    if (System.IO.File.Exists(fileName))
                    {
                        System.IO.File.Delete(fileName);
                    }
                }
            }
        }
        // GET: BlobInfo
        public ActionResult Index()
        {
            return View();
        }
        [OutputCache(CacheProfile="Cache1Year")]
        public ActionResult Image(string id)
        {
            string filePath=GetImagePhysicalPath(id);
            if (string.IsNullOrEmpty(filePath))
            {
                return HttpNotFound();
            }
            else
            {
                return File(filePath,"image/jpeg");
            }
        }
        public ActionResult ImageViewer(string id)
        {
            if (string.IsNullOrEmpty(GetImagePhysicalPath(id)))
            {
                return HttpNotFound();
            }
            else
            {
                var blob=CacheHelper.Blobs.Where(x => x.SeoFileName.Equals(id,StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (blob==null)
                {
                    return HttpNotFound();
                }
                else
                {
                    BlobInfoImageViewerModel model=new BlobInfoImageViewerModel();
                    model.ImageUrl=string.Format("~/blobinfo/image/{0}",blob.SeoFileName);
                    model.Title=blob.SeoFileName.Substring(0,id.Length-4).Replace("-"," ");
                    model.SeoFileName=blob.SeoFileName;
                    return View(model);
                }
            }
        }
        [OutputCache(CacheProfile="Cache1Year")]
        public ActionResult Thumbnail(string id,int width=0,int height=0)
        {
            if (width<1)
            {
                width=thumbnailWidth;
            }
            if (height<1)
            {
                height=thumbnailHeight;
            }
            string fileName=string.Format("{0}-{1}x{2}.jpg",id,width,height);
            string filePath=HostingEnvironment.MapPath(string.Format("{0}/{1}",thumbnailDirectory,fileName));
            if (!System.IO.File.Exists(filePath))
            {
                using (System.Drawing.Image originalImage=System.Drawing.Image.FromFile(HostingEnvironment.MapPath(string.Format("~/app_data/blob/{0}.jpg",id))))
                {
                    using (Bitmap thumbnailBM=new Bitmap(width,height,PixelFormat.Format32bppPArgb))
                    {
                        thumbnailBM.SetResolution(originalImage.HorizontalResolution,originalImage.VerticalResolution);
                        using (Graphics thumbnailG=Graphics.FromImage(thumbnailBM))
                        {
                            thumbnailG.CompositingQuality=CompositingQuality.HighQuality;
                            thumbnailG.SmoothingMode=SmoothingMode.HighQuality;
                            thumbnailG.DrawImage(originalImage,0,0,width,height);
                        }
                        thumbnailBM.Save(filePath,ImageFormat.Jpeg);
                    }
                }
            }
            return File(filePath,"image/jpeg");
        }
        [Route("admin/blobinfoform")]
        public ActionResult BlobInfoForm()
        {
            if (SessionHelper.IsAdmin)
            {
                return View();
            }
            else
            {
                return new HttpUnauthorizedResult();
            }
        }
        [Route("admin/removeblob")]
        [HttpPost()]
        public ActionResult RemoveBlob(string id)
        {
            if (SessionHelper.IsAdmin)
            {
                string fileName=GetImagePhysicalPath(id);
                if (System.IO.File.Exists(fileName))
                {
                    System.IO.File.Delete(fileName);
                    RemoveThumbnails(id);
                    CacheHelper.ResetBlobs();
                }
                return Redirect("~/admin/gallerymanager");
            }
            else
            {
                return new HttpUnauthorizedResult();
            }
        }
    }
}